import { Injectable } from '@angular/core';
import { Http, Response, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/toPromise';

import { LoginForm } from './login-form.class';

@Injectable()
export class LoginService {

    constructor(private _http: Http) { }

    login(url: string, loginForm: LoginForm): Promise<any> {
        let params: URLSearchParams = new URLSearchParams();
        params.set('username', loginForm.username);
        params.set('password', loginForm.password);
        params.set('authCode', loginForm.authCode);

        return this._http.get(url, {search: params}).toPromise()
                    .then(this.extractData)
                    .catch(this.handleError);
    }

    extractData(res: Response) {
        let body = res.json();
        return body || { };
    }

    handleError(error: Response | any) {
        let errMsg: string;
        if (error instanceof Response) {
            if (error.status > 200) {
                errMsg = '网络异常';
              if(error.status === 500){
                errMsg = '登录失效请重新登录';
              }
            } else {
                errMsg = '网络异常';
            }
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        return Promise.reject(errMsg);
    }
}
